#!/usr/bin/env python
#
#       proxy.py
#
#       Copyright 2009 Chris Glass <tribaal@gmail.com>
#
#       This program is free software: you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation, either version 3 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program.  If not, see <http://www.gnu.org/licenses/>.


#Twisted proxy!
from twisted.web.http import HTTPChannel, HTTPFactory, Request
from twisted.internet import reactor, threads
from properties import props
from handler import GlassCacheHandler
#import threading
import sys

class GlassCacheRequest(Request):
    def process(self):

        raw_headers = self.requestHeaders.getAllRawHeaders()
        headers = {}
        for header in raw_headers:
            headers[header[0]] = header[1]

        # We defer execution of the complicated cache interface inside
        # a thread so that the webserver remains non-blocking
        deferred = threads.deferToThread(
            self.channel.factory.cache.handle_request, self.uri, headers)

        def writeListToResponse(response_dict):
            if response_dict:
                # We got the item from the database!
                
                #Headers...
                assert response_dict['headers']
                for name, value in response_dict['headers'].iteritems():
                    self.setHeader(name, value)
                
                #print type
                
                data = response_dict['content']

                self.setResponseCode(200)

                self.write(data)

            else:
                self.setResponseCode(404)
                self.write("404... Not found :(")

        def handleError(failure):
            print 'Error!!!'
            print failure

        deferred.addCallback(writeListToResponse)
        deferred.addCallback(lambda _:self.finish())
        deferred.addErrback(handleError)

class GlassCacheProtocol(HTTPChannel) :

     def requestFactory(self, *args):
        return GlassCacheRequest(*args)


class GlassCacheFactory(HTTPFactory):
    protocol = GlassCacheProtocol
    properties = props().load_properties() 
    port = properties['port']
    # This is the interface to the cache.
    # It's in the factory = it's a shared object!
    cache = GlassCacheHandler(properties)

sys.path.append('..')
f = GlassCacheFactory()
f.protocol = GlassCacheProtocol
print "Running cache on port %s" % f.port
reactor.listenTCP(int(f.port), f)

reactor.run()




